
//
//  HomeStatusListViewModel.swift
//  微博
//
//  Created by xm on 2018/3/22.
//  Copyright © 2018年 xm. All rights reserved.
//

import Foundation
import SDWebImage

class HomeStatusListViewModel{
    
    lazy var dataList=[HomeStatusViewModel]()
    
    
    /// <#Description#>
    ///
    /// - Parameters:
    ///   - isPullUp: 是否时上拉加载更多
    ///   - completion: 完成回掉
    func loadData(isPullUp: Bool,completion:@escaping (Bool)->()) ->() {
        
        //since_id 下拉刷新
        //max_id 上拉加载更多
        let sinceId:Int64 = isPullUp ? 0 : (dataList.first?.status?.id ?? 0)
        var maxId: Int64 = !isPullUp ? 0 : (dataList.last?.status?.id ?? 0)
            maxId=maxId>0 ?maxId-1 :0 //大于0就减去1 条数就对了
        
        NetworkManager.shared.getStatusList(sinceId:sinceId,maxId:maxId) { (rdata, isSuccess) in
            if(isSuccess){
                // 判断它是否为nil 而且是否是一个字典
                guard let resDict = rdata as? [String: Any] else{
                    //finish(false,0)
                    completion(false)
                    return
                }
                // 判断resDict["statuses"] 是否为nil 而且是否是一个[[string:any]]
                guard let resList = resDict["statuses"] as? [[String: Any]] else{
                    // finish(false,0)
                    completion(false)
                    return
                }
                guard let tempList = NSArray.yy_modelArray(with: HomeStatusModel.self, json: resList ?? [])
                    as? [HomeStatusModel]
                    else{
                         completion(false)
                     return
                }
                
                var array = [HomeStatusViewModel]()
                //遍历构造组装数据
                for model in tempList {
                    let hsv=HomeStatusViewModel()
                    hsv.status=model
                    array.append(hsv)
                } 
                
                if isPullUp{//上拉加载更多
                     self.dataList=self.dataList + array;
                }else{
                     //下拉刷新，放到最前面
                     self.dataList=array + self.dataList;
                }
                //循环下载单张图片微博中的图片
                self.downLoadSinglePicture(array: array, completion: completion)
            }else{
                completion(false)
            }
        }
    }
    
    func downLoadSinglePicture(array: [HomeStatusViewModel]?,completion:@escaping (Bool)->()) {
        guard let array = array else {
            completion(true)
            return
        }
        //创建一个任务调度组
        let group=DispatchGroup()
        
        for statusViewModel in array{
             //单张图片的微博
            if statusViewModel.picModelList != nil && statusViewModel.picModelList?.count == 1{
                let urlStr=(statusViewModel.picModelList![0]).thumbnail_pic ?? ""
                let url = URL(string: urlStr)
                group.enter()
                SDWebImageManager.shared().loadImage(with:url, options: [], progress: nil, completed: { (image, _, _, _,_,_) in
                    if image != nil {
                        statusViewModel.calcSinglePictureViewSize(image: image!)
                    }
                    group.leave()
                })
            }
        }
        
        //任务组，所有子任务全部结束
        group.notify(queue: DispatchQueue.main) {
            completion(true)
        }
    }
    
}
